package top.tagao.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tagao.yygh.common.helper.HttpRequestHelper;
import top.tagao.yygh.enums.OrderStatusEnum;
import top.tagao.yygh.enums.PaymentStatusEnum;
import top.tagao.yygh.enums.PaymentTypeEnum;
import top.tagao.yygh.hosp.client.HospitalFeignClient;
import top.tagao.yygh.model.order.OrderInfo;
import top.tagao.yygh.model.order.PaymentInfo;
import top.tagao.yygh.order.mapper.PaymentInfoMapper;
import top.tagao.yygh.order.service.OrderService;
import top.tagao.yygh.order.service.PaymentService;
import top.tagao.yygh.vo.order.SignInfoVo;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/15 15:59
 */
@Service
public class PaymentServiceImpl extends
        ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    /**
     * 保存交易记录
     * @param orderInfo
     * @param paymentType 支付类型（1：微信 2：支付宝）
     */
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer paymentType) {
        // 1.根据订单id和支付类型,查询支付记录表是否存在相同订单
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderInfo.getId());
        wrapper.eq("payment_type",paymentType);
        Integer count = baseMapper.selectCount(wrapper);

        if (count > 0) {
            return;
        }
        // 2.添加记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + "|" + orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        baseMapper.insert(paymentInfo);

    }

    /**
     * @date  更新订单状态
     * @param out_trade_no
     * @param resultMap
     */
    @Override
    @Transactional
    public void paySuccess(String out_trade_no, Map<String, String> resultMap) {

        // 1. 根据订单编号得到支付记录 (数据库表) yygh_order.payment_info
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("out_trade_no",out_trade_no);
        wrapper.eq("payment_type", PaymentTypeEnum.WEIXIN.getStatus());
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);
        // 2. 更新支付记录信息
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setTradeNo(resultMap.get("transaction_id"));
        paymentInfo.setCallbackContent(resultMap.toString());
        baseMapper.updateById(paymentInfo);

        // 3. 根据订单号得到订单信息  (数据库表) yygh_order.order_info
        // 4. 更新订单详情信息
        OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderInfo.setUpdateTime(new Date());
        orderService.updateById(orderInfo);

        // 5. 调用医院接口，更新订单支付信息 (数据库表) yygh_manager.order_info
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("hoscode",orderInfo.getHoscode());
        requestMap.put("hosRecordId",orderInfo.getHosRecordId());
        requestMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(requestMap, signInfoVo.getSignKey());
        requestMap.put("sign",sign);
        JSONObject request = HttpRequestHelper.sendRequest(requestMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
    }

    /**
     * @date   获取支付记录
     */
    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("payment_type", paymentType);
        return baseMapper.selectOne(queryWrapper);
    }
}
